package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.RequestManager;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import org.apache.http.Header;

public class UserPhotoFragment extends BaseFragment implements OnClickListener {
  //public static final String EXTRA_BITMAP = "com.isunland.managesystem.ui.EXTRA_BITMAP";
  public static final String EXTRA_PATH = "com.isunland.managesystem.ui.EXTRA_PATH";
  // 文件上传成功后在服务器上的路径.
  public static final String EXTRA_RESULT = "com.isunland.managesystem.ui.EXTRA_RESULT";
  // 选择头像
  private static final int CHOOSE_PHOTO = 0;
  private CurrentUser mCurrentUser;
  private ImageView ivNewUserPhoto;
  //private Bitmap mBitmap;
  private String mPath = "";// 更换头像后图片路径
  private String mFilePath = "";// 传递过来图片路径

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitleCustom(R.string.editPhoto);
    mCurrentUser = CurrentUser.newInstance(getActivity());
    mFilePath = (String) getArguments().getSerializable(EXTRA_PATH);
    LogUtil.i(mFilePath);
    //setHasOptionsMenu(true);
    //BaseVolleyActivity mActivity = (BaseVolleyActivity) getActivity();
    // mBitmap=getArguments().getParcelable(EXTRA_BITMAP);
    //if (NavUtils.getParentActivityName(getActivity()) != null) {
    //	( (BaseVolleyActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    //
    //}
    //( (BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle(R.string.editPhoto);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;

      default:
        break;
    }

    return true;
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_user_photo, container, false);
    ivNewUserPhoto = (ImageView) v.findViewById(R.id.iv_new_user_photo);
    Button ibChangePhoto = (Button) v.findViewById(R.id.ib_change_photo);
    Button ibSavePhoto = (Button) v.findViewById(R.id.ib_save_photo);
    ibChangePhoto.setOnClickListener(this);
    ibSavePhoto.setOnClickListener(this);
    //		ivNewUserPhoto.setOnClickListener(new OnClickListener() {
    //
    //		@Override
    //		public void onClick(View v) {
    //			File file=new File(mDocPath);
    //			Intent intent = new Intent();
    //			intent.setAction(android.content.Intent.ACTION_VIEW);
    //			intent.setDataAndType(Uri.fromFile(file), "image/*");
    //			startActivity(intent);
    //
    //		}
    //	});
    // //如果地址为空显示默认头像
    // if (!"".equals(mUrlImage)) {
    //
    // //根据地址解析出头像
    // Toast.makeText(getActivity(), "解析头像!", Toast.LENGTH_SHORT).show();
    // Bitmap bm=BitmapFactory.decodeFile(mUrlImage);
    // ivNewUserPhoto.setImageBitmap(bm);
    // }
    if (mFilePath != null) {

      setImageBypath(mFilePath);
    }
    return v;
  }

  // 登录人头像显示
  public void setImageBypath(String filePath) {
    String urlImage = ApiConst.getDownLoadUrlByGet(filePath);
    ImageLoader imageLoader = RequestManager.getImageLoader();

    ImageListener listener =
        ImageLoader.getImageListener(ivNewUserPhoto, R.drawable.photo, R.drawable.photo);

    imageLoader.get(urlImage, listener);
  }

  @Override public void onClick(View arg0) {
    switch (arg0.getId()) {
      // 拍照或显示图片列表
      case R.id.ib_change_photo:
        DialogFragment dialog;
        FragmentManager fm = getActivity().getSupportFragmentManager();
        dialog = new ChooseUserPhotoDialogFragment();// 头像
        dialog.setTargetFragment(UserPhotoFragment.this, CHOOSE_PHOTO);
        dialog.show(fm, "");
        break;
      // 上传保存头像
      case R.id.ib_save_photo:

        savePhoto();
        break;

      default:
        break;
    }
  }

  private void savePhoto() {
    if ("".equals(mPath)) {
      Toast.makeText(getActivity(), "文件已上传!", Toast.LENGTH_SHORT).show();
    } else {
      MyUtils.showDialogLoading(getActivity());
      new FileNetWorkUtil(getActivity()).upLoadFile(mPath, ApiConst.URL_UPLOAD_FILE, "sys_user",
          mCurrentUser.getUserId(), new myUpLoadHandler(), true);
    }
  }

  @SuppressWarnings("deprecation") private class myUpLoadHandler extends AsyncHttpResponseHandler {
    @Override public void onStart() {
      MyUtils.showDialogLoading(getActivity());
      super.onStart();
    }

    @Override public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
      MyUtils.dismissDialog();
      ToastUtil.show(R.string.fileUploadFailure);
    }

    @Override public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
      MyUtils.dismissDialog();
      LogUtil.i("arg2==" + new String(arg2));
      try {

        SuccessMessage result = new Gson().fromJson(new String(arg2), SuccessMessage.class);

        if (result != null && result.getResult() != null && result.getResult().equals("1")) {
          Toast.makeText(getActivity(), R.string.fileUploadSuccess, Toast.LENGTH_SHORT).show();
          // 上传成功,保存图片路径到用户信息中,这样第二次打开的时候就自动刷新头像了.
          CurrentUser.newInstance(getActivity()).setPicture(result.getMessage());
          Intent resultIntent = new Intent();
          resultIntent.putExtra("result", mPath);//图像文件绝对路径.
          getActivity().setResult(Activity.RESULT_OK, resultIntent);
          getActivity().finish();
        } else {
          Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
        }
      } catch (Exception e) {
        // Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
      }
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == CHOOSE_PHOTO) {
      // mBitmap=data.getParcelableExtra(ChooseUserPhotoDialogFragment.EXTRA_BITMAP);
      byte[] bis = data.getByteArrayExtra(ChooseUserPhotoDialogFragment.EXTRA_BITMAP);
      Bitmap bitmap = BitmapFactory.decodeByteArray(bis, 0, bis.length);

      mPath = data.getStringExtra(ChooseUserPhotoDialogFragment.EXTRA_PATH);
      LogUtil.i(mPath);
      ivNewUserPhoto.setImageBitmap(bitmap);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  public static UserPhotoFragment newInstance(String path) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_PATH, path);
    UserPhotoFragment fragment = new UserPhotoFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
